package cn.homework.day05;

import java.util.Random;

public class Demo2 {
    public static void main(String[] args) {
        // 定义奖项数组,并为其设置值
        Award[] awards = new Award[4];
        awards[0] = new Award("一等奖", 1);
        awards[1] = new Award("二等奖", 2);
        awards[2] = new Award("三等奖", 3);
        awards[3] = new Award("谢谢惠顾", 4);
        // 补全代码 给奖项添加权重
        awards[0].setLow(0);
        awards[0].setHigt(0);
        awards[1].setLow(1);
        awards[1].setHigt(2);
        awards[2].setLow(3);
        awards[2].setHigt(5);
        awards[3].setLow(6);
        awards[3].setHigt(9);

        int totalWeight = 10;

        // 创建Random对象
        Random random = new Random();
        for (int j = 0; j < 100; j++) {
            // 获取0到总权重数据之间的随机数
            int i = random.nextInt(totalWeight);
            // System.out.println(i);
            // 利用二分查找根据权重数从奖项数组中获取对应的奖项
            Award aw = binarySearch(awards, i);
            // 控制台输出奖项名称
            System.out.println("恭喜XXX先生/女士获得：" + aw.getName());
        }

    }

    // 二分查找实现 返回奖项 找不到 返回null
    public static Award binarySearch(Award[] awards, int num) {
        int min = 0;
        int max = awards.length - 1;
        while (min <= max) {
            int mid = (min + max) / 2;
            if (num < awards[mid].getLow()) {
                max = mid - 1;
            } else if (num > awards[mid].getHigt()) {
                min = mid + 1;
            } else {
                return awards[mid];
            }
        }
        return null;
    }
}
